package org.jeecg.modules.business.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.entity.BusDict;
import org.jeecg.modules.business.entity.BusDictItem;
import org.jeecg.modules.business.entity.BusHotel;
import org.jeecg.modules.business.service.IBusDictItemService;
import org.jeecg.modules.business.service.IBusDictService;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 业务字典配置表
 * @Author: jeecg-boot
 * @Date:   2023-03-06
 * @Version: V1.0
 */
@Api(tags="业务字典配置表")
@RestController
@RequestMapping("/business/busDictItem")
@Slf4j
public class BusDictItemController extends JeecgController<BusDictItem, IBusDictItemService> {
	@Autowired
	private IBusDictItemService busDictItemService;

	 @Autowired
	private IBusDictService busDictService;

	/**
	 * 分页列表查询
	 *
	 * @param busDictItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "业务字典配置表-分页列表查询")
	@ApiOperation(value="业务字典配置表-分页列表查询", notes="业务字典配置表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusDictItem>> queryPageList(BusDictItem busDictItem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusDictItem> queryWrapper = QueryGenerator.initQueryWrapper(busDictItem, req.getParameterMap());
		Page<BusDictItem> page = new Page<BusDictItem>(pageNo, pageSize);
		IPage<BusDictItem> pageList = busDictItemService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param busDictItem
	 * @return
	 */
	@AutoLog(value = "业务字典配置表-添加")
	@ApiOperation(value="业务字典配置表-添加", notes="业务字典配置表-添加")
	//@RequiresPermissions("business:bus_dict_item_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusDictItem busDictItem) {
		busDictItem.setDelFlag(CommonConstant.DEL_FLAG_0);
		if(busDictItem.getTenantId() == null || busDictItem.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busDictItem.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		busDictItemService.save(busDictItem);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busDictItem
	 * @return
	 */
	@AutoLog(value = "业务字典配置表-编辑")
	@ApiOperation(value="业务字典配置表-编辑", notes="业务字典配置表-编辑")
	//@RequiresPermissions("business:bus_dict_item_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusDictItem busDictItem) {
//		busDictItemService.updateById(busDictItem);
		if(busDictItem.getTenantId() == null || busDictItem.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busDictItem.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		BusDictItem editModel = busDictItemService.getById(busDictItem.getId());
		editModel.setDictId(busDictItem.getDictId());
		editModel.setItemText(busDictItem.getItemText());
		editModel.setItemValue(busDictItem.getItemValue());
		editModel.setDescription(busDictItem.getDescription());
		editModel.setSortOrder(busDictItem.getSortOrder());
		editModel.setStatus(busDictItem.getStatus());
		busDictItemService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "业务字典配置表-通过id删除")
	@ApiOperation(value="业务字典配置表-通过id删除", notes="业务字典配置表-通过id删除")
	//@RequiresPermissions("business:bus_dict_item_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busDictItemService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "业务字典配置表-批量删除")
	@ApiOperation(value="业务字典配置表-批量删除", notes="业务字典配置表-批量删除")
	//@RequiresPermissions("business:bus_dict_item_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busDictItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "业务字典配置表-通过id查询")
	@ApiOperation(value="业务字典配置表-通过id查询", notes="业务字典配置表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusDictItem> queryById(@RequestParam(name="id",required=true) String id) {
		BusDictItem busDictItem = busDictItemService.getById(id);
		if(busDictItem==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busDictItem);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busDictItem
    */
    //@RequiresPermissions("business:bus_dict_item_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusDictItem busDictItem) {
        return super.exportXls(request, busDictItem, BusDictItem.class, "业务字典配置表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_dict_item_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusDictItem.class);
    }

	 /**
	  * 根据 dictId 查询字典值
	  */
	 @GetMapping("/queryByParentIdList")
	 public Result<?> queryByOrgCodeForAddressList(
			 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			 @RequestParam(name = "dictId",required = false) String dictId,
			 BusDictItem busDictItem
	 ) {
		 IPage page = new Page(pageNo, pageSize);
		 IPage<BusDictItem> pageList = busDictItemService.queryItemByParentId(dictId, busDictItem, page);
		 List<BusDictItem> list = pageList.getRecords();

		 // 记录所有出现过的 user, key = userId
		 Map<String, JSONObject> hasUser = new HashMap<>(list.size());

		 JSONArray resultJson = new JSONArray(list.size());

//		 for (BusDictItem item : list) {
//			 String userId = item.getId();
//			 // userId
//			 JSONObject getModel = hasUser.get(userId);
//			 // 之前已存在过该用户，直接合并数据
//			 if (getModel != null) {
//				 String departName = getModel.get("departName").toString();
//				 getModel.put("departName", (departName + " | " + item.getDepartName()));
//			 } else {
//				 // 将用户对象转换为json格式，并将部门信息合并到 json 中
//				 JSONObject json = JSON.parseObject(JSON.toJSONString(item));
//				 json.remove("id");
//				 json.put("userId", userId);
//				 json.put("departId", item.getDepartId());
//				 json.put("departName", item.getDepartName());
////                json.put("avatar", item.getSysUser().getAvatar());
//				 resultJson.add(json);
//				 hasUser.put(userId, json);
//			 }
//		 }

		 IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
		 result.setRecords(resultJson.toJavaList(JSONObject.class));
		 return Result.ok(result);
	 }

	 /**
	  * 字典值重复校验
	  * @param busDictItem
	  * @param request
	  * @return
	  */
	 @RequestMapping(value = "/dictItemCheck", method = RequestMethod.GET)
	 @ApiOperation("字典重复校验接口")
	 public Result<Object> doDictItemCheck(BusDictItem busDictItem, HttpServletRequest request) {
		 Long num = Long.valueOf(0);
		 LambdaQueryWrapper<BusDictItem> queryWrapper = new LambdaQueryWrapper<BusDictItem>();
		 queryWrapper.eq(BusDictItem::getItemValue,busDictItem.getItemValue());
		 queryWrapper.eq(BusDictItem::getDictId,busDictItem.getDictId());
		 queryWrapper.eq(BusDictItem::getHotelId,busDictItem.getHotelId());
		 if (StringUtils.isNotBlank(busDictItem.getId())) {
			 // 编辑页面校验
			 queryWrapper.ne(BusDictItem::getId,busDictItem.getId());
		 }
		 num = busDictItemService.count(queryWrapper);
		 if (num == 0) {
			 // 该值可用
			 return Result.ok("该值可用！");
		 } else {
			 // 该值不可用
			 log.info("该值不可用，系统中已存在！");
			 return Result.error("该值不可用，系统中已存在！");
		 }
	 }

	 /**
	  * 列表查询
	  *
	  * @param busDictItem
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="业务字典配置表-列表查询", notes="业务字典配置表-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<List<BusDictItem>> queryList(BusDictItem busDictItem,
												HttpServletRequest req) {
		 QueryWrapper<BusDictItem> queryWrapper = QueryGenerator.initQueryWrapper(busDictItem, req.getParameterMap());
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			 queryWrapper.eq("tenant_id",user.getRelTenantIds());
		 }
		 List<BusDictItem> list = new ArrayList<>();
		 String dictName = req.getParameter("dictName");
		 String hotelId = req.getParameter("hotelId");
		 if(oConvertUtils.isNotEmpty(dictName)){
			 LambdaQueryWrapper<BusDict> queryDictWrapper = new LambdaQueryWrapper<>();
			 queryDictWrapper.eq(BusDict::getDictName,dictName);
			 queryDictWrapper.eq(BusDict::getTenantId,user.getRelTenantIds());
			 queryDictWrapper.eq(BusDict::getHotelId,hotelId);
			 BusDict busDict = busDictService.getOne(queryDictWrapper);

			 if (busDict != null) {
				 //queryWrapper.ne(BusDictItem::getDictId,busDict.getId());
				 queryWrapper.eq("dict_id",busDict.getId());
				 queryWrapper.eq("status",1);
				 queryWrapper.eq("del_flag",0);
				 list = busDictItemService.list(queryWrapper);
			 }
		 }
		 return Result.OK(list);
	 }
}
